package com.imooc.chart.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ImageMerger {

    /**
     * 合并多个图片为一张图片
     *
     * @param imagesPaths 图片路径列表
     * @param outputImagePath 输出图片路径
     * @param type 图片类型（例如 "jpg", "png" 等）
     * @throws IOException 如果读取/写入图片时出错
     */
    public static void mergeImages(List<String> imagesPaths, String outputImagePath, String type) throws IOException {
        // 计算总宽度和最大高度
        int totalWidth = 0;
        int maxHeight = 0;
        for (String path : imagesPaths) {
            BufferedImage image = ImageIO.read(new File(path));
            totalWidth += image.getWidth();
            maxHeight = Math.max(maxHeight, image.getHeight());
        }

        // 创建合并后的图片缓冲区
        BufferedImage mergedImage = new BufferedImage(totalWidth, maxHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = mergedImage.createGraphics();

        // 填充背景为白色（可根据需要更改）
        g2.setPaint(Color.WHITE);
        g2.fillRect(0, 0, totalWidth, maxHeight);

        // 合并图片
        int widthCumulative = 0;
        for (String path : imagesPaths) {
            BufferedImage image = ImageIO.read(new File(path));
            g2.drawImage(image, widthCumulative, 0, null);
            widthCumulative += image.getWidth();
        }
        g2.dispose();

        // 保存合并后的图片
        ImageIO.write(mergedImage, type, new File(outputImagePath));
    }
}
